<template>
  <a-spin :spinning="confirmLoading">
    <!--统计区域-->
    <div class="jeecg-basic-table-form-container">
      <BillStatisticsCard class="enter-y" :billStatistics="billStatistics"/>
    </div>
    <!--查询区域-->
    <div class="jeecg-basic-table-form-container" style="margin-bottom: -10px;">
      <a-form @keyup.enter.native="searchQuery" :model="queryParam" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row :gutter="24">
          <a-col :lg="6">
            <a-form-item label="开票类型">
              <j-dict-select-tag placeholder="请选择开票类型" v-model:value="queryParam.type" dictCode="caishui_bill_type"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6">
            <a-form-item label="开票类目">
              <a-cascader placeholder="请选择开票类目"
                          :field-names="{ label: 'title', value: 'key' }"
                          :options="options" :show-search="true" @change="handleSelectCategory"/>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :lg="12">
              <a-form-item label="申请时间">
                <a-date-picker showTime value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择开始时间" v-model:value="queryParam.createTime_begin" class="query-group-cust" />
                <span class="query-group-split-cust">~</span>
                <a-date-picker showTime value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择结束时间" v-model:value="queryParam.createTime_end" class="query-group-cust" />
              </a-form-item>
            </a-col>
            <a-col :lg="12">
              <a-form-item label="提交时间">
                <a-date-picker showTime value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择开始时间" v-model:value="queryParam.submitTime_begin" class="query-group-cust" />
                <span class="query-group-split-cust">~</span>
                <a-date-picker showTime value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择结束时间" v-model:value="queryParam.submitTime_end" class="query-group-cust" />
              </a-form-item>
            </a-col>
            <a-col :lg="12">
              <a-form-item label="审核时间">
                 <a-date-picker showTime value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择开始时间" v-model:value="queryParam.checkTime_begin" class="query-group-cust" />
                 <span class="query-group-split-cust">~</span>
                 <a-date-picker showTime value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择结束时间" v-model:value="queryParam.checkTime_end" class="query-group-cust" />
              </a-form-item>
            </a-col>
            <a-col :lg="12">
              <a-form-item label="完成时间">
                 <a-date-picker showTime value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择开始时间" v-model:value="queryParam.finishTime_begin" class="query-group-cust" />
                 <span class="query-group-split-cust">~</span>
                 <a-date-picker showTime value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择结束时间" v-model:value="queryParam.finishTime_end" class="query-group-cust" />
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-col :lg="6">
                <a-button type="primary" preIcon="ant-design:search-outlined" @click="searchQuery">查询</a-button>
                <a-button type="primary" preIcon="ant-design:reload-outlined" @click="searchReset" style="margin-left: 8px">重置</a-button>
                <a @click="toggleSearchStatus = !toggleSearchStatus" style="margin-left: 8px">
                  {{ toggleSearchStatus ? '收起' : '展开' }}
                  <Icon :icon="toggleSearchStatus ? 'ant-design:up-outlined' : 'ant-design:down-outlined'" />
                </a>
              </a-col>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :columns="tableColumns">
      <!--插槽:table标题-->
      <template #tableTitle>
        <span style="margin-bottom: 30px;margin-top: 10px;width: 100%;">
          <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined"> 申请开票</a-button>
<!--          <a-button :loading="exportIconLoading" type="primary" preIcon="ant-design:export-outlined" @click="handleExportXls"> 导出</a-button>-->
        </span>
        <br/>
        <div>
          <a-radio-group v-model:value="activeKey" @change="handleRadioChange">
            <a-radio-button value="0">　待提交　</a-radio-button>
<!--            <a-badge :count="10" :overflow-count="99">-->
<!--              <a-radio-button value="1">　审核中　</a-radio-button>-->
<!--            </a-badge>-->
            <a-radio-button value="1">　审核中　</a-radio-button>
            <a-radio-button value="2">　开票中　</a-radio-button>
            <a-radio-button value="3">审核驳回</a-radio-button>
            <a-radio-button value="7">开票完成</a-radio-button>
          </a-radio-group>
        </div>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)"/>
      </template>
      <!--开票类型插槽-->
      <template #typeSlot="{record}">
        <a-tag v-if="record.type==1" color="green">{{record.type_dictText}}</a-tag>
        <a-tag v-if="record.type==2" color="red">{{record.type_dictText}}</a-tag>
      </template>
      <!--收件类型插槽-->
      <template #receivedTypeSlot="{record}">
        <a-badge v-if="record.receivedType==1" color="green" :text="record.receivedType_dictText" />
        <a-badge v-if="record.receivedType==2" color="red" :text="record.receivedType_dictText" />
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <CaishuiBillModal ref="registerModal" @success="handleSuccess"></CaishuiBillModal>
    <CaishuiBillDetailModal ref="registerDetailModal" @success="handleSuccess"></CaishuiBillDetailModal>
    <!-- 验证手机区域 -->
    <VerifyPhone ref="registerVerifyPhone" @success="handleVerifyPhoneSuccess"></VerifyPhone>
  </a-spin>
</template>

<script lang="ts" name="caishuiBill-caishuiBill" setup>
import { onMounted, reactive, ref } from "vue";
import { BasicTable, TableAction } from "/@/components/Table";
import { useListPage } from "/@/hooks/system/useListPage";
import { columns, columns1, columns2, columns3, columns4 } from "./CaishuiBill.data";
import {
  batchDelete,
  deleteOne,
  getExportUrl,
  getImportUrl,
  list,
  queryBillStatistics,
  statusOne
} from "./CaishuiBill.api";
import CaishuiBillModal from "./components/CaishuiBillModal.vue";
import CaishuiBillDetailModal from "./components/CaishuiBillDetailModal.vue";
import BillStatisticsCard from "./components/BillStatisticsCard.vue";
import VerifyPhone from "/@/layouts/default/header/components/user-dropdown/VerifyPhone.vue";
import JDictSelectTag from "/@/components/Form/src/jeecg/components/JDictSelectTag.vue";
import { loadTreeRoot } from "/@/api/common/api";
import type { CascaderProps } from "ant-design-vue";
import { useMessage } from "/@/hooks/web/useMessage";

const queryParam = ref<any>({});
  const toggleSearchStatus = ref<boolean>(false);
  const registerModal = ref();
  const registerDetailModal = ref();
  const { createMessage } = useMessage();
  const registerVerifyPhone = ref();
  const exportIconLoading = ref<boolean>(false);
  const confirmLoading = ref<boolean>(false);
  const activeKey = ref('0');
  const options = ref<CascaderProps['options']>([]);
  const tableColumns = ref<any>(columns);
  const billStatistics = ref<any>({});
  const categoryId = ref('');

  //注册table数据
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: '开票记录',
      api: list,
      canResize:false,
      useSearchForm: false,
      striped: true,
      showIndexColumn: true,
      actionColumn: {
        width: 150,
        fixed: 'right',
      },
      beforeFetch: (params) => {
        params.status = activeKey.value;
        params.categoryId = categoryId.value;
        return Object.assign(params, queryParam.value);
      },
    },
    exportConfig: {
      name: "开票记录",
      url: getExportUrl,
      success: exportXlsSuccess
    },
	  importConfig: {
	    url: getImportUrl,
	    success: handleSuccess
	  },
  });
  const [registerTable, { reload, collapseAll, updateTableDataRecord, findTableDataRecord, getDataSource }, { rowSelection, selectedRowKeys }] = tableContext;
  const labelCol = reactive({
    xs: { span: 24 },
    sm: { span: 6 },
  });
  const wrapperCol = reactive({
    xs: { span: 24 },
    sm: { span: 16 },
  });

  onMounted(async () => {
    await queryBillStatistics({}).then((res) => {
      billStatistics.value = res;
    });
    await loadTreeRoot({pcode:'A02',async: false}).then((res) => {
      options.value = res;
    });
  });

  /**
   * 选择开票栏目事件
   * @param value
   * @param optios
   */
  function handleSelectCategory(value,optios){
    if(value instanceof Array){
      categoryId.value = value.join('/');
    }
  }

  /**
   * 改变单选框事件
   * @param e
   */
  function handleRadioChange(e){
    if(activeKey.value==='0'){
      tableColumns.value = columns;
    }else if(activeKey.value==='1'){
      tableColumns.value = columns.concat(...columns1);
    }else if(activeKey.value==='2'){
      tableColumns.value = columns.concat(...columns1,...columns2);
    }else if(activeKey.value==='3'){
      tableColumns.value = columns.concat(...columns1,...columns2,...columns3);
    }else if(activeKey.value==='7'){
      tableColumns.value = columns.concat(...columns1,...columns2,...columns3,...columns4);
    };
    searchQuery();//查询
  }

  /**
   * 新增事件
   */
  function handleAdd() {
    registerModal.value.disableSubmit = false;
    registerModal.value.add(billStatistics.value.billCanAmount);
  }
  
  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    record.billCanAmount = billStatistics.value.billCanAmount;
    registerModal.value.disableSubmit = false;
    registerModal.value.edit(record);
  }
   
  /**
   * 详情
   */
  function handleDetail(record: Recordable) {
    registerDetailModal.value.disableSubmit = true;
    registerDetailModal.value.edit(record);
  }

  /**
   * 提交
   */
  function handleSubmitFp(record: Recordable) {
    registerVerifyPhone.value.show(record.id,1);
  }

  /**
   * 验证手机完成之后提交事件
   */
  async function handleVerifyPhoneSuccess(data) {
    confirmLoading.value = true;
    await statusOne({
      id: data.id,
      status: data.status,
      captcha: data.captcha }).then((res) => {
      if (res.success) {
        createMessage.success(res.message);
        handleSuccess();
      } else {
        createMessage.warning(res.message);
      }
    }).finally(() => {
      confirmLoading.value = false;
    });
  }

  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteOne({ id: record.id }, handleSuccess);
  }

  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
  }
   
  /**
   * 成功回调
   */
  function handleSuccess() {
    confirmLoading.value = false;
    (selectedRowKeys.value = []) && reload();
    //重新查询开票统计
    queryBillStatistics({}).then((res) => {
      billStatistics.value = res;
    });
  }
   
  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        label: '提交',
        ifShow: record.status==0,
        icon: 'ant-design:check-circle-outlined',
        onClick: handleSubmitFp.bind(null, record),
      },
      {
        label: '详情',
        ifShow: record.status!=0,
        icon: 'ant-design:info-outlined',
        onClick: handleDetail.bind(null, record),
      },
    ];
  }
   
  /**
   * 下拉操作栏
   */
  function getDropDownAction(record) {
    return [
      {
        label: '编辑',
        ifShow: record.status==0,
        icon: 'ant-design:edit-outlined',
        onClick: handleEdit.bind(null, record),
      },
      {
        label: '详情',
        ifShow: record.status==0,
        icon: 'ant-design:info-outlined',
        onClick: handleDetail.bind(null, record),
      }, {
        label: '删除',
        ifShow: record.status==0,
        icon: 'ant-design:delete-outlined',
        popConfirm: {
          title: '是否确认删除？',
          confirm: handleDelete.bind(null, record),
        }
      }
    ]
  }

  /**
   * 查询
   */
  function searchQuery() {
    reload();
  }
  
  /**
   * 重置
   */
  function searchReset() {
    queryParam.value = {};
    selectedRowKeys.value = [];
    //刷新数据
    reload();
  }

  /**
   * 导出
   */
  function handleExportXls() {
    exportIconLoading.value = true;
    onExportXls();
  }

  /**
   * 导出成功回调
   */
  function exportXlsSuccess(data) {
    exportIconLoading.value = false;
  }

</script>

<style lang="less" scoped>
  .jeecg-basic-table-form-container {
    .table-page-search-submitButtons {
      display: block;
      margin-bottom: 10px;
      white-space: nowrap;
    }
    .query-group-cust{
      width: calc(50% - 15px);
      min-width: 100px !important;
    }
    .query-group-split-cust{
      width: 30px;
      display: inline-block;
      text-align: center
    }
  }
</style>
